package orm

import (
	"go-toy/util"
	"time"
)

func init() {
	// reset pool settings to default values
	poolConfig := util.Viper.GetStringMap("db.pool")
	if len(poolConfig) > 0 {
		maxIdleConns := util.Viper.GetInt("db.pool.maxIdleConns")
		maxOpenConns := util.Viper.GetInt("db.pool.maxOpenConns")
		connMaxLifetime := util.Viper.GetInt("db.pool.connMaxLifetime")

		// initialize database connection
		sqlDB, err := DB.DB()
		if err != nil {
			panic("failed to get sql.DB: " + err.Error())
		}

		if maxIdleConns > 0 {
			sqlDB.SetMaxIdleConns(maxIdleConns)
		}
		if maxOpenConns > 0 {
			sqlDB.SetMaxOpenConns(maxOpenConns)
		}
		if connMaxLifetime > 0 {
			sqlDB.SetConnMaxLifetime(time.Duration(connMaxLifetime) * time.Second)
		}

		util.PrintlnSuccess("Use connection pool which is defined in config file.")
	} else {
		util.PrintlnTrace("No connection pool settings found in config.json, use default settings.")
	}
}
